// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use log::{error, warn};
use maestro_derive::MsgTag;
use ohmw_derive::{Decode, Encode};

#[derive(Encode, Decode, MsgTag)]
#[msg_tag(case = "snake_case")]
pub struct GetProjectListRet {
    pub project_list: Vec<String>,
}

pub async fn get_project_list(workspace_path: &str) -> GetProjectListRet {
    let mut project_list = Vec::new();
    let Ok(mut read_dir) = tokio::fs::read_dir(workspace_path).await else {
        warn!("Workspace path does not exist or is not a directory: {}, try to create it", workspace_path);
        if let Err(e) = tokio::fs::create_dir_all(workspace_path).await {
            error!("Failed to create workspace directory: {}", e);
        }
        return GetProjectListRet { project_list };
    };

    loop {
        let res = read_dir.next_entry().await;
        let Ok(entry) = res else {
            error!("Failed to read directory entry");
            continue;
        };
        let Some(entry) = entry else {
            break;
        };
        
        if entry.file_type().await.is_ok_and(|t| t.is_dir()) {
            project_list.push(entry.file_name().to_string_lossy().to_string());
        }
    }

    GetProjectListRet { project_list }
}
